﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using SARS.Biz;
using SARS.Entity;

namespace SARS.Course.Group
{
    public partial class StudentGroupEdit : Page
    {
        private readonly GroupBO groupBiz = new GroupBO();
        private readonly UserBO userBiz = new UserBO();
        private GroupEntity group;

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetNoStore();
            if (!string.IsNullOrEmpty(Request.QueryString["gid"]))
            {
                int groupID = Int32.Parse(Request.QueryString["gid"]);
                group = groupBiz.RetrieveGroupById(groupID);
                group.GroupMembers = userBiz.RetrieveStudentByGroupId(groupID);
                group.GroupTutorial = userBiz.RetrieveTutorsByGroupId(groupID);

                if (!IsPostBack)
                {
                    hdlabel.Text = group.GroupName;
                    lblGroupName.Text = group.GroupName;
                    lbGroupCourse.Text = group.Course.CourseInfo;
                    lblGroupTutors.Text = group.GroupTutorialNames;

                    gvGroupStudent.DataSource = group.GroupMembers;
                    gvGroupStudent.DataBind();
                }
            }
            else
            {
                Response.Redirect("Group.aspx");
            }
        }

        protected void btnOk_OnClick(object sender, EventArgs e)
        {
            List<string> checkStudent = GetCheckedStudent();
            foreach (string studentId in checkStudent)
            {
                groupBiz.RemoveStudentGroup(group.GroupID, Int32.Parse(studentId));
            }
            Response.Redirect("StudentGroupDetail.aspx?gid=" + group.GroupID);
        }

        protected void btnCancel_OnClick(object sender, EventArgs e)
        {
            Response.Redirect("StudentGroupDetail.aspx?gid=" + group.GroupID);
        }

        private List<string> GetCheckedStudent()
        {
            var checkedIds = new List<string>();

            foreach (GridViewRow gvrow in gvGroupStudent.Rows)
            {
                string index = gvGroupStudent.DataKeys[gvrow.RowIndex].Value.ToString();
                bool result = ((CheckBox) gvrow.FindControl("cbDelete")).Checked;
                if (result)
                {
                    checkedIds.Add(index);
                }
            }

            return checkedIds;
        }
    }
}